<template>
  <el-select
    v-model="selectValue"
    @change="handleChange"
    :placeholder="placeholder"
    :clearable="clearable"
    v-loading="loading"
  >
    <el-option
      v-for="(item, index) in optionList"
      :key="index"
      :value="item[keyValue]"
      :label="item[labelValue]"
    >
      <span>{{ item[labelValue] }}</span>
      <span v-if="showCode" style="float: right; color: #ccc">{{
        item[keyValue]
      }}</span>
    </el-option>
  </el-select>
</template>

<script setup name="EtSelect">
import { reactive, toRefs } from "vue";
const emit = defineEmits(["change"]);
const props = defineProps({
  api: {
    type: Function,
    default: () => {},
  },
  searchParams: {
    type: Object,
    default: () => {},
  },
  placeholder: {
    type: String,
    default: "请选择",
  },
  keyValue: {
    type: String,
    default: "code",
  },
  labelValue: {
    type: String,
    default: "name",
  },
  showCode: {
    type: Boolean,
    default: false,
  },
  clearable: {
    type: Boolean,
    default: false,
  },
  showLoading: {
    type: Boolean,
    default: true,
  },
});
const {
  api,
  searchParams,
  placeholder,
  keyValue,
  labelValue,
  showCode,
  clearable,
  showLoading,
} = toRefs(props);
const selectValue = defineModel();
const selectName = defineModel("name");
const optionList = ref([]);
const loading = ref(false);
const param = reactive({
  pageNum: 1,
  pageSize: 1000,
});
const handleChange = (value) => {
  let selects = [];
  if (Array.isArray(value)) {
    selects = optionList.value.filter((el) => {
      value.includes(el[keyValue.value]);
    });
    const names = selects.map((el) => el[labelValue.value]);
    selectName.value = names.join(',');
    emit("change", selects);
    return;
  }
  selects = optionList.value.filter((el) => {
   return value === el[keyValue.value];
  });
  selectName.value = selects[0][labelValue.value];
  emit("change", selects.length ? selects[0] : null);
};
const loadData = async () => {
  if (showLoading) loading.value = true;
  if (api) {
    try {
      const res = await api.value({ ...param, ...searchParams.value });
      loading.value = false;
      optionList.value = res.rows;
      return res.rows;
    } catch (error) {
      console.log(error);
    }
  }
  loading.value = false;
  return [];
};
onMounted(() => {
  loadData();
});
</script>

<style lang="scss" scoped></style>
